<template>
  <view class="edit-container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 编辑表单 -->
    <scroll-view v-else class="form-scroll" scroll-y>
      <form @submit="handleSubmit">
        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">基本信息</view>
          
          <view class="form-item">
            <text class="label required">信息类型</text>
            <picker 
              :value="selectedTypeIndex" 
              :range="listingTypes" 
              @change="onTypeChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ listingTypes[selectedTypeIndex] || '请选择' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label required">公司名称</text>
            <input 
              v-model="formData.company_name"
              placeholder="请输入公司/个体户名称"
              class="form-input"
              maxlength="100"
            />
          </view>

          <view class="form-item">
            <text class="label">注册省份</text>
            <picker 
              :value="selectedProvinceIndex" 
              :range="provinces" 
              @change="onProvinceChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ provinces[selectedProvinceIndex] || '请选择省份' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">注册城市</text>
            <picker
              :value="selectedCityIndex"
              :range="cities"
              @change="onCityChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ cities[selectedCityIndex] || '请选择城市' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">成立时间</text>
            <picker 
              mode="date" 
              :value="formData.establishment_date"
              @change="onDateChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ formData.establishment_date || '请选择日期' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>
        </view>

        <!-- 财务信息 -->
        <view class="form-section">
          <view class="section-title">财务信息</view>
          
          <view class="form-item">
            <text class="label">价格设置</text>
            <radio-group @change="onPriceTypeChange">
              <view class="price-options">
                <label class="radio-item">
                  <radio 
                    value="negotiable"
                    :checked="formData.is_negotiable" 
                    color="#22c55e"
                  />
                  <text>面议</text>
                </label>
                <label class="radio-item">
                  <radio 
                    value="fixed"
                    :checked="!formData.is_negotiable" 
                    color="#22c55e"
                  />
                  <text>固定价格</text>
                </label>
              </view>
            </radio-group>
          </view>

          <view v-if="!formData.is_negotiable" class="form-item">
            <text class="label">转让价格（万元）</text>
            <input 
              v-model.number="formData.price"
              placeholder="请输入价格"
              type="number"
              class="form-input"
            />
          </view>

          <view class="form-item">
            <text class="label">注册资本</text>
            <picker 
              :value="selectedCapitalIndex" 
              :range="capitalRanges" 
              @change="onCapitalChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ capitalRanges[selectedCapitalIndex] || '请选择注册资本范围' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">实缴状态</text>
            <picker 
              :value="selectedPaidIndex" 
              :range="paidStatuses" 
              @change="onPaidChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ paidStatuses[selectedPaidIndex] || '请选择实缴状态' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>
        </view>

        <!-- 公司信息 -->
        <view class="form-section">
          <view class="section-title">公司信息</view>
          
          <view class="form-item">
            <text class="label">{{ getCompanyTypeLabel() }}</text>
            <picker 
              :value="selectedCompanyTypeIndex" 
              :range="companyTypes" 
              @change="onCompanyTypeChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ companyTypes[selectedCompanyTypeIndex] || '请选择' + getCompanyTypeLabel() }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">税务状态</text>
            <picker
              :value="selectedTaxIndex"
              :range="taxStatuses"
              @change="onTaxChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ taxStatuses[selectedTaxIndex] || '请选择税务状态' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">纳税等级</text>
            <picker
              :value="selectedTaxGradeIndex"
              :range="taxGrades"
              @change="onTaxGradeChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ taxGrades[selectedTaxGradeIndex] || '请选择纳税等级' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">银行开户</text>
            <picker 
              :value="selectedBankIndex" 
              :range="bankStatuses" 
              @change="onBankChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ bankStatuses[selectedBankIndex] || '请选择银行开户状态' }}</text>
                <text class="picker-arrow">></text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">银行流水</text>
            <input
              v-model="formData.bank_flow"
              placeholder="请输入银行流水情况"
              class="form-input"
              maxlength="255"
            />
          </view>
        </view>

        <!-- 特殊资质 -->
        <view class="form-section">
          <view class="section-title">特殊资质</view>

          <view class="checkbox-group">
            <view class="checkbox-item" @click="toggleAsset('has_trademark')">
              <checkbox
                :checked="formData.has_trademark"
                color="#22c55e"
              />
              <text class="checkbox-label">商标</text>
            </view>

            <view class="checkbox-item" @click="toggleAsset('has_patent')">
              <checkbox
                :checked="formData.has_patent"
                color="#22c55e"
              />
              <text class="checkbox-label">专利</text>
            </view>

            <view class="checkbox-item" @click="toggleAsset('has_software_copyright')">
              <checkbox
                :checked="formData.has_software_copyright"
                color="#22c55e"
              />
              <text class="checkbox-label">软件著作权</text>
            </view>

            <view class="checkbox-item" @click="toggleAsset('has_license_plate')">
              <checkbox
                :checked="formData.has_license_plate"
                color="#22c55e"
              />
              <text class="checkbox-label">车牌</text>
            </view>

            <view class="checkbox-item" @click="toggleAsset('has_social_security')">
              <checkbox
                :checked="formData.has_social_security"
                color="#22c55e"
              />
              <text class="checkbox-label">社保</text>
            </view>

            <view class="checkbox-item" @click="toggleAsset('has_bidding_history')">
              <checkbox
                :checked="formData.has_bidding_history"
                color="#22c55e"
              />
              <text class="checkbox-label">投标记录</text>
            </view>
          </view>
        </view>

        <!-- 详细描述 -->
        <view class="form-section">
          <view class="section-title">详细描述</view>
          
          <view class="form-item">
            <textarea 
              v-model="formData.description"
              placeholder="请详细描述公司情况、转让原因等（选填）"
              class="form-textarea"
              maxlength="500"
            />
            <text class="char-count">{{ formData.description.length }}/500</text>
          </view>
        </view>

        <!-- 审核状态提示（仅被拒绝时显示） -->
        <view v-if="isRejected" class="form-section audit-notice">
          <view class="audit-notice-header">
            <text class="notice-icon">⚠️</text>
            <text class="notice-title">审核未通过</text>
          </view>
          <view class="rejection-reason" v-if="rejectionReason">
            <text class="reason-label">拒绝原因：</text>
            <text class="reason-text">{{ rejectionReason }}</text>
          </view>
          <view class="notice-tip">请根据拒绝原因修改内容后重新提交审核</view>
        </view>
      </form>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <view v-if="isRejected" class="button-group">
        <button 
          class="save-btn"
          :disabled="isSubmitting"
          @click="handleSubmit"
        >
          {{ isSubmitting ? '保存中...' : '保存修改' }}
        </button>
        <button 
          class="submit-audit-btn"
          :disabled="isSubmitting || resubmitting"
          @click="resubmitAudit"
        >
          {{ resubmitting ? '提交中...' : '提交审核' }}
        </button>
      </view>
      <button 
        v-else
        class="submit-btn"
        :disabled="isSubmitting"
        @click="handleSubmit"
      >
        {{ isSubmitting ? '保存中...' : '保存修改' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { listingAPI, userAPI, utils } from '@/utils/api.js'
import { getProvinces, getCitiesByProvince, areaUtils } from '@/utils/areaData.js'

// 响应式数据
const isLoading = ref(true)
const isSubmitting = ref(false)
const listingId = ref(null)
const isRejected = ref(false)
const rejectionReason = ref('')
const resubmitting = ref(false)

// 表单数据
const formData = reactive({
  listing_type: '',
  company_name: '',
  registration_province: '',
  registration_city: '',
  establishment_date: '',
  price: null,
  is_negotiable: false,
  registered_capital_range: '',
  paid_in_status: '',
  company_type: '',
  tax_status: '',
  bank_account_status: '',
  bank_flow: '',
  has_trademark: false,
  has_patent: false,
  has_software_copyright: false,
  has_license_plate: false,
  has_social_security: false,
  has_bidding_history: false,
  description: ''
})

// 选择器数据
const listingTypes = ['公司', '个体户', '代账户']
const selectedTypeIndex = ref(-1)

// 使用完整的省市数据
const provinces = getProvinces()
const selectedProvinceIndex = ref(-1)

const cities = ref(['请先选择省份'])
const selectedCityIndex = ref(-1)

const capitalRanges = ['10万以下', '10-50万', '50-100万', '100-500万', '500-1000万', '1000万以上']
const selectedCapitalIndex = ref(-1)

const paidStatuses = ['已实缴', '未实缴', '不确定']
const selectedPaidIndex = ref(-1)

// 原始公司类型选项
const originalCompanyTypes = ['普通公司', '国家局公司', '上市公司', '不确定']
// 个体户类型选项
const individualTypes = ['个人经营', '家庭经营']
// 当前显示的类型选项（动态变化）
const companyTypes = ref(['普通公司', '国家局公司', '上市公司', '不确定'])
const selectedCompanyTypeIndex = ref(-1)

const taxStatuses = ['未登记', '小规模', '一般纳税人', '未开业', '不确定']
const selectedTaxIndex = ref(-1)

const taxGrades = ['A', 'B', 'M', 'C', 'D', '未开通']
const selectedTaxGradeIndex = ref(-1)

const bankStatuses = ['已开户', '未开户', '不确定']
const selectedBankIndex = ref(-1)

// 生命周期
onLoad((options) => {
  const { id } = options
  if (id) {
    listingId.value = id
    loadListingData(id)
  } else {
    isLoading.value = false
    uni.showToast({
      title: '缺少信息ID',
      icon: 'error'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})

// 方法定义
const loadListingData = async (id) => {
  try {
    isLoading.value = true

    const response = await listingAPI.getListingDetail(id)

    if (response.success) {
      const data = response.data

      // 填充表单数据
      formData.listing_type = data.listing_type
      formData.company_name = data.company_name
      formData.registration_province = data.registration_province || ''
      formData.registration_city = data.registration_city || ''
      formData.establishment_date = data.establishment_date || ''
      formData.price = data.price
      formData.is_negotiable = data.is_negotiable
      formData.registered_capital_range = data.registered_capital_range || ''
      formData.paid_in_status = data.paid_in_status || ''
      formData.company_type = data.company_type || ''
      formData.tax_status = data.tax_status || ''
      formData.tax_grade = data.tax_grade || ''
      formData.bank_account_status = data.bank_account_status || ''
      formData.shareholder_background = data.shareholder_background || ''
      formData.has_trademark = data.has_trademark
      formData.has_patent = data.has_patent
      formData.has_software_copyright = data.has_software_copyright
      formData.has_license_plate = data.has_license_plate
      formData.has_social_security = data.has_social_security
      formData.has_bidding_history = data.has_bidding_history
      formData.description = data.description || ''

      // 设置选择器索引
      selectedTypeIndex.value = listingTypes.indexOf(data.listing_type)
      selectedProvinceIndex.value = provinces.indexOf(data.registration_province)

      // 如果有省份数据，先更新城市列表，再设置城市索引
      if (data.registration_province) {
        cities.value = getCitiesByProvince(data.registration_province)
        selectedCityIndex.value = cities.value.indexOf(data.registration_city)
      } else {
        selectedCityIndex.value = -1
      }

      selectedCapitalIndex.value = capitalRanges.indexOf(data.registered_capital_range)
      selectedPaidIndex.value = paidStatuses.indexOf(data.paid_in_status)
      // 根据信息类型设置公司类型选项
      updateCompanyTypeOptions(data.listing_type)
      
      // 设置公司类型索引
      const displayCompanyType = getDisplayCompanyTypeValue(data.company_type, data.listing_type)
      selectedCompanyTypeIndex.value = companyTypes.value.indexOf(displayCompanyType)
      selectedTaxIndex.value = taxStatuses.indexOf(data.tax_status)
      selectedTaxGradeIndex.value = taxGrades.indexOf(data.tax_grade)
      selectedBankIndex.value = bankStatuses.indexOf(data.bank_account_status)

      // 检查审核状态
      console.log('审核状态:', data.audit_status)
      console.log('审核备注:', data.audit_comment)
      isRejected.value = data.audit_status === '已拒绝'
      rejectionReason.value = data.audit_comment || ''
      console.log('isRejected:', isRejected.value)
      console.log('rejectionReason:', rejectionReason.value)

    } else {
      utils.handleError(new Error(response.message), '获取信息失败')
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }

  } catch (error) {
    utils.handleError(error, '获取信息失败')
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } finally {
    isLoading.value = false
  }
}

const onTypeChange = (e) => {
  selectedTypeIndex.value = e.detail.value
  formData.listing_type = listingTypes[e.detail.value]
  
  // 根据信息类型动态调整公司类型选项
  updateCompanyTypeOptions(formData.listing_type)
}

const onProvinceChange = (e) => {
  selectedProvinceIndex.value = e.detail.value
  const selectedProvince = provinces[e.detail.value]
  formData.registration_province = selectedProvince

  // 重置城市选择
  selectedCityIndex.value = -1
  formData.registration_city = ''

  // 更新城市列表
  if (selectedProvince) {
    cities.value = getCitiesByProvince(selectedProvince)
  } else {
    cities.value = ['请先选择省份']
  }
}

const onCityChange = (e) => {
  selectedCityIndex.value = e.detail.value
  formData.registration_city = cities.value[e.detail.value]
}

const onDateChange = (e) => {
  formData.establishment_date = e.detail.value
}

const onPriceTypeChange = (e) => {
  const value = e.detail.value
  formData.is_negotiable = value === 'negotiable'
  if (formData.is_negotiable) {
    formData.price = null
  }
}

const onCapitalChange = (e) => {
  selectedCapitalIndex.value = e.detail.value
  formData.registered_capital_range = capitalRanges[e.detail.value]
}

const onPaidChange = (e) => {
  selectedPaidIndex.value = e.detail.value
  formData.paid_in_status = paidStatuses[e.detail.value]
}

const onCompanyTypeChange = (e) => {
  selectedCompanyTypeIndex.value = e.detail.value
  formData.company_type = getActualCompanyTypeValue(companyTypes.value[e.detail.value], formData.listing_type)
}

const onTaxChange = (e) => {
  selectedTaxIndex.value = e.detail.value
  formData.tax_status = taxStatuses[e.detail.value]
}

const onTaxGradeChange = (e) => {
  selectedTaxGradeIndex.value = e.detail.value
  formData.tax_grade = taxGrades[e.detail.value]
}

const onBankChange = (e) => {
  selectedBankIndex.value = e.detail.value
  formData.bank_account_status = bankStatuses[e.detail.value]
}



// 根据信息类型更新公司类型选项
const updateCompanyTypeOptions = (listingType) => {
  if (listingType === '个体户') {
    companyTypes.value = [...individualTypes]
  } else {
    companyTypes.value = [...originalCompanyTypes]
  }
}

// 获取公司类型标签
const getCompanyTypeLabel = () => {
  return formData.listing_type === '个体户' ? '个体户类型' : '公司类型'
}

// 获取实际的公司类型值（映射个体户类型到现有枚举）
const getActualCompanyTypeValue = (displayValue, listingType) => {
  if (listingType === '个体户') {
    // 将个体户类型映射到现有的公司类型枚举值
    if (displayValue === '个人经营') {
      return '普通公司'  // 复用普通公司枚举
    } else if (displayValue === '家庭经营') {
      return '国家局公司'  // 复用国家局公司枚举
    }
  }
  return displayValue
}

// 获取显示的公司类型值（从实际值映射到显示值）
const getDisplayCompanyTypeValue = (actualValue, listingType) => {
  if (listingType === '个体户') {
    // 将实际存储的公司类型映射到个体户类型显示
    if (actualValue === '普通公司') {
      return '个人经营'
    } else if (actualValue === '国家局公司') {
      return '家庭经营'
    }
  }
  return actualValue
}

// 切换资产状态
const toggleAsset = (field) => {
  formData[field] = !formData[field]
}

const handleSubmit = async () => {
  if (isSubmitting.value) return

  try {
    // 基本验证
    if (!formData.listing_type) {
      uni.showToast({
        title: '请选择信息类型',
        icon: 'error'
      })
      return
    }

    if (!formData.company_name.trim()) {
      uni.showToast({
        title: '请输入公司名称',
        icon: 'error'
      })
      return
    }

    isSubmitting.value = true

    // 准备提交数据
    const submitData = { ...formData }

    // 处理价格
    if (submitData.is_negotiable) {
      submitData.price = null
    } else if (submitData.price) {
      submitData.price = parseFloat(submitData.price)
    }

    // 清理空值
    Object.keys(submitData).forEach(key => {
      if (submitData[key] === '' || submitData[key] === null) {
        delete submitData[key]
      }
    })

    const response = await listingAPI.updateListing(listingId.value, submitData)

    if (response.success) {
      uni.showToast({
        title: '修改成功',
        icon: 'success'
      })

      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      utils.handleError(new Error(response.message), '修改失败')
    }

  } catch (error) {
    utils.handleError(error, '修改失败')
  } finally {
    isSubmitting.value = false
  }
}

const resubmitAudit = async () => {
  try {
    resubmitting.value = true
    
    const result = await listingAPI.resubmitAudit(listingId.value)
    
    if (result.success) {
      uni.showToast({
        title: '已重新提交审核',
        icon: 'success'
      })
      
      // 重置状态
      isRejected.value = false
      rejectionReason.value = ''
      
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: result.message || '提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('重新提交审核失败:', error)
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    })
  } finally {
    resubmitting.value = false
  }
}
</script>

<style scoped>
.edit-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-scroll {
  flex: 1;
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 15rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.label.required::after {
  content: '*';
  color: #ef4444;
  margin-left: 5rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: white;
}

.form-picker {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  background: white;
}

.picker-content {
  height: 100%;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #333;
}

.picker-arrow {
  color: #999;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: white;
}

.char-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.checkbox-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  padding: 20rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  background: #f9f9f9;
  cursor: pointer;
  transition: background-color 0.2s;
}

.checkbox-item:active {
  background: #e5e5e5;
}

.checkbox-label {
  color: #333;
}

.bottom-actions {
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #eee;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn:disabled {
  background: #ccc;
}

.price-options {
  display: flex;
  gap: 40rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
}

.audit-notice {
  background-color: #fff2e8;
  border: 1rpx solid #ffd591;
  border-radius: 8rpx;
  padding: 24rpx;
}

.audit-notice-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.notice-icon {
  margin-right: 8rpx;
  font-size: 28rpx;
}

.notice-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #d46b08;
}

.rejection-reason {
  margin-bottom: 12rpx;
}

.reason-label {
  font-size: 26rpx;
  color: #8c8c8c;
}

.reason-text {
  font-size: 26rpx;
  color: #d46b08;
  margin-left: 8rpx;
}

.notice-tip {
  font-size: 24rpx;
  color: #8c8c8c;
  line-height: 1.4;
}

.button-group {
  display: flex;
  gap: 20rpx;
}

.save-btn {
  flex: 1;
  height: 90rpx;
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.save-btn:disabled {
  background: #cccccc;
  color: #999;
}

.submit-audit-btn {
  flex: 1;
  height: 90rpx;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-audit-btn:disabled {
  background: #cccccc;
  color: #999;
}
</style>
